package com.lunker.moneyrecord;

import java.util.Calendar;
import java.util.Formatter;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class NewRecordActivity extends Activity implements OnClickListener {
	
	private static final int DATE_DIALOG_ID = 0;
	private static final int STRING_DIALOG_ID = 1;
	private static final String ZERO = "0";
	public static final int RESULT_YES = 2;
	public static final int RESULT_NO = 3;
	
	private TextView txt_amount;
	private TextView txt_date;
	private Spinner spr_category;
	private TextView txt_comment;
	private boolean dot = false;
	private StringBuilder amount = new StringBuilder(ZERO);
	private SQLiteDatabase mydb = null; 
	private int[] categoryIds = null; //IDs map to catalog names at the same position in array.
	private int year;
	private int month;
	private int day;
	private int categoryId;
	private Calendar today = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_record);
		
		mydb = new MyDatabaseOpenHelper(this).getWritableDatabase();		
		txt_amount = (TextView) findViewById(R.id.txt_newRecordAmountValue);
		txt_date = (TextView) findViewById(R.id.txt_newRecordDateValue);
		spr_category = (Spinner) findViewById(R.id.spr_newRecordCategory);
		txt_comment = (TextView) findViewById(R.id.txt_newRecordCommentValue);
		//Set to default date to today, and default catalog to the first catalog in array.		
		today = Calendar.getInstance();
		year = today.get(Calendar.YEAR);
		month = today.get(Calendar.MONTH);
		day = today.get(Calendar.DAY_OF_MONTH);
		updateDisplayDate(year, month, day);
		categoryIds = getResources().getIntArray(R.array.category_id);
		categoryId = categoryIds[0];		
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, 
				R.array.category_name, R.layout.text_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
		spr_category.setAdapter(adapter);
		spr_category.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int pos, long id) {
				categoryId = categoryIds[pos];
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				//Do nothing.
			}
		});
		
		if (getIntent().getStringExtra("rid") != null) {
			loadOldRecord(getIntent().getStringExtra("rid"));
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			Calendar c = Calendar.getInstance();
			return new DatePickerDialog(
					this,
					new DatePickerDialog.OnDateSetListener() {
						
						@Override
						public void onDateSet(DatePicker view, int year, int monthOfYear,
								int dayOfMonth) {
							
							NewRecordActivity.this.year = year;
							NewRecordActivity.this.month = monthOfYear;
							NewRecordActivity.this.day = dayOfMonth;
							updateDisplayDate(year, monthOfYear, dayOfMonth);
						}
					},
					c.get(Calendar.YEAR),
					c.get(Calendar.MONTH),
					c.get(Calendar.DAY_OF_MONTH));
		case STRING_DIALOG_ID:
			return new TextInputDialog(
					this,
					new TextInputDialog.OnSetStringListener() {
						
						@Override
						public void onSetString(String str) {
							NewRecordActivity.this.txt_comment.setText(str);
						}
					});
		}
		
		return null;
	}

	@Override
	protected void onDestroy() {
		if (mydb != null) {
			mydb.close();
		}
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.txt_newRecordDateValue:
			showDialog(DATE_DIALOG_ID);
			break;
		case R.id.txt_newRecordCommentValue:
			showDialog(STRING_DIALOG_ID);
			break;
		case R.id.btn_clear:
			dot = false;
			amount = new StringBuilder(ZERO);
			txt_amount.setText(ZERO);
			break;
		case R.id.btn_dot:
			if (!dot) {
				dot = true;
				amount.append(".");
				txt_amount.setText(amount.toString());
			}
			break;
		case R.id.btn_0:
		case R.id.btn_1:
		case R.id.btn_2:
		case R.id.btn_3:
		case R.id.btn_4:
		case R.id.btn_5:
		case R.id.btn_6:
		case R.id.btn_7:
		case R.id.btn_8:
		case R.id.btn_9:
			if (amount.toString().equals(ZERO)) {
				//Don't start with 0.
				amount.replace(0, 1, ((Button) v).getText().toString());
			} else {
				amount.append(((Button) v).getText());
			}
			txt_amount.setText(amount.toString());		
			break;
		case R.id.btn_newRecordConfirm:
			//Escape "'".
			String comment = txt_comment.getText().toString();
			
			if (comment != null) {
				comment = comment.replace("'", "''");	
			} else {
				comment = "";
			}
			
			//Values to insert/update.
			ContentValues values = new ContentValues(6);
			values.put("year", Integer.valueOf(year));
			values.put("month", Integer.valueOf(month));
			values.put("day", Integer.valueOf(day));
			values.put("amount", txt_amount.getText().toString());
			values.put("category", Integer.valueOf(categoryId));
			values.put("comment", comment);
			
			if (getIntent().getStringExtra("rid") != null) {
				//Update an old record.
				mydb.update(
						"money_record", 
						values, 
						"rid = ?",
						new String[] {
								getIntent().getStringExtra("rid")
						});
				Toast.makeText(this, getString(R.string.one_record_is_modified), 
						Toast.LENGTH_SHORT).show();
			} else {
				// Add a new record.
				mydb.insert("money_record", null, values);
				Toast.makeText(this, getString(R.string.one_record_is_added), 
						Toast.LENGTH_SHORT).show();
			}
			
			updateWidget();
			setResult(RESULT_YES);
			finish();
			break;
		case R.id.btn_newRecordCancel:
			setResult(RESULT_NO);
			finish();
			break;
		}
	}
	
	private void updateWidget () {
		new WidgetProvider().notifyChange(this);
	}
	
	private void updateDisplayDate (int year, int month, int day) {
		txt_date.setText(new Formatter().format("%d-%02d-%02d" , 
				year, (month + 1), day).toString());
	}
	
	private void loadOldRecord (String rid) {
		Cursor cr = mydb.query(
				"money_record",
				new String[] {
						"year",
						"month",
						"day",
						"category",
						"comment",
						"amount"
				},
				"rid = ?",
				new String[] {
						rid
				},
				null,
				null,
				null);
		startManagingCursor(cr);		
		cr.moveToFirst();
		
		//Load data into UI.
		//Comment.
		txt_comment.setText(cr.getString(cr.getColumnIndex("comment")));
		//Amount.
		String amt = Float.toString(cr.getFloat(cr.getColumnIndex("amount")));
		txt_amount.setText(amt);
		amount = new StringBuilder(amt);
		//Date.
		year = cr.getInt(cr.getColumnIndex("year"));
		month = cr.getInt(cr.getColumnIndex("month"));
		day = cr.getInt(cr.getColumnIndex("day"));
		updateDisplayDate(year, month, day);
		
		//Category.
		int index = 0;
		int cid = cr.getInt(cr.getColumnIndex("category"));
		
		for (int i = 0; i < categoryIds.length; i++) {
			if (cid == categoryIds[i]) {
				index = i;
			}
		}
		
		spr_category.setSelection(index);
		categoryId = categoryIds[index];
	}
}
